package com.minxi.web.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class JspServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName = req.getParameter("userName");
        String passWord = req.getParameter("passWord");
        String userPhone = req.getParameter("userPhone");
        String userSex = req.getParameter("userSex");
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/student?serverTimezone=Asia/Shanghai";
            String user = "root";
            String pwd = "123456";
            connection = DriverManager.getConnection(url, user, pwd);
            String sql = "insert into user_info(user_name,User_pwd,User_phone,user_sex)values(?,?,?,?);";
            preparedStatement = connection.prepareStatement(sql);

            preparedStatement.setString(1, userName);
            preparedStatement.setString(2, passWord);
            preparedStatement.setString(3, userPhone);
            preparedStatement.setInt(4, Integer.parseInt(userSex));

            int rs = preparedStatement.executeUpdate();

            if (rs > 0) {
                resp.sendRedirect("jsp/home.jsp");
            } else {
                resp.sendRedirect("jsp/add.jsp");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                preparedStatement.close();
                connection.close();
            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
